package geektime.spring.springbucks.service.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageInfo;
import geektime.spring.springbucks.mapper.CoffeeMapper;
import geektime.spring.springbucks.model.Coffee;
import geektime.spring.springbucks.service.CoffeeService;
import geektime.spring.springbucks.utils.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.RowBounds;
import org.joda.money.CurrencyUnit;
import org.joda.money.Money;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

@Service
@Slf4j
public class CoffeeServiceImpl implements CoffeeService {

    @Resource
    private CoffeeMapper coffeeMapper;
    @Resource
    private RedisUtil redisUtil;

    public static final String COFFEE_ALL = "coffee_all";

    @Override
    public List<Coffee> findAll() {

        coffeeMapper.findAllWithRowBounds(new RowBounds(1, 3))
                .forEach(c -> log.info("Page(1) Coffee {}", c));
        coffeeMapper.findAllWithRowBounds(new RowBounds(2, 3))
                .forEach(c -> log.info("Page(2) Coffee {}", c));

        log.info("===================");

        coffeeMapper.findAllWithRowBounds(new RowBounds(1, 0))
                .forEach(c -> log.info("Page(1) Coffee {}", c));

        log.info("===================");

        coffeeMapper.findAllWithParam(1, 3)
                .forEach(c -> log.info("Page(1) Coffee {}", c));
        List<Coffee> list = coffeeMapper.findAllWithParam(2, 3);
        //存入缓存
        String s = JSON.toJSONString(list);
        redisUtil.set(COFFEE_ALL, s);
        PageInfo<Coffee> page = new PageInfo<>(list);
        log.info("PageInfo: {}", page);
        return list;
    }

    @Override
    public List<Coffee> findAllByRedis() {
        Object o = redisUtil.get(COFFEE_ALL);
        List<Coffee> coffees = JSON.parseArray(o.toString(), Coffee.class);
        log.info(o.toString());
        return coffees;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void insertOrUpdateCoffee() {
        Coffee c = Coffee.builder().name("tom")
                .price(Money.of(CurrencyUnit.of("CNY"), 25.0)).build();
        int count = coffeeMapper.save(c);
        log.info("db-insert-row:{}", count);
        Coffee c1 = Coffee.builder().id(5L)
                .price(Money.of(CurrencyUnit.of("CNY"), 25.0)).build();
        int row = coffeeMapper.updateCoffeePrice(c1);
        log.info("db-update-row:{}", row);
        int dRow = coffeeMapper.deleteByPrimaryKey(1L);
        log.info("db-delete-row:{}", dRow);
        int i = 1 / 0;
    }
}
